package main

import (
	"gdfs-service/conf"
	"gdfs-service/controller"
	"gdfs-service/db"
	"gdfs-service/logcat"
	"gdfs-service/socket"
	"gdfs-service/sync"
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"strconv"
	"strings"
	"time"
)

func main() {
	//初始化配置读取工具
	config := conf.LoadConfig("")
	//初始化日志工具
	logcat.InitLogger(config.Viper.GetString("log.path"), "info")
	//初始化数据库
	db.InitDB(config)
	db.RunServerDB()
	setNodeConf()
	//生成store_id
	storeid := generateStoreId()
	logcat.Info("###存储服务id:", storeid, "长度:", len(storeid))
	conf.SetStoreid(storeid)
	//配置
	sizestr := config.GetEnvValue("storage.maxsize")
	size, _ := strconv.Atoi(sizestr)
	conf.SetMaxSize(size)
	regip := config.GetEnvValue("gdfs.registerConfig.IpAddr") //注册ip
	regport := config.GetEnvValue("gdfs.registerConfig.Port")
	webport := config.GetEnvValue("web.port")
	weight, _ := strconv.Atoi(config.Viper.GetString("gdfs.registerConfig.weight"))
	//创建tcp连接
	socket.RunTcpConn(regip, regport, webport, storeid, weight)
	//开启同步检测
	sync.RunSyncData()
	//http
	r := gin.Default()
	r.Use(LogerMiddleware())
	r.Use(gin.Recovery())
	r.GET("/gdfs/api/file/getByteArray", controller.GetFileByteArray) //获取文件流接口
	r.GET("/gdfs/api/file/getFileBase64", controller.GetFileBase64)   //获取文件base64接口
	r.GET("/gdfs/api/file/search", controller.SearchFile)             //查询文件是否存在
	r.POST("/gdfs/api/file/upload", controller.UploadFile)            //上传文件接口
	r.POST("/gdfs/api/file/remove", controller.BatchDeleteFile)       //批量删除文件接口
	r.POST("/gdfs/api/file/update", controller.UpdateFileByKey)       //更新文件接口
	r.POST("/gdfs/api/file/syncfile", controller.RecvSyncFile)        //增量文件同步接口
	r.Run(":" + webport)
}

func setNodeConf() {
	var sinfo db.StoreInfo
	db.GetDB().First(&sinfo)
	if sinfo != (db.StoreInfo{}) {
		if sinfo.NodeID != "" {
			nf := socket.GetNodeConf()
			nf.NodeID = sinfo.NodeID
			nf.NoticeStores = nil
		}
	}
}

//生成uuid
func generateStoreId() string {
	var storeinfos []db.StoreInfo
	db.GetDB().Find(&storeinfos)
	total := len(storeinfos)
	if total == 0 {
		uuid := uuid.NewV4()
		var storeinfo db.StoreInfo
		storeid := strings.Replace(uuid.String(), "-", "", -1)
		storeinfo.StoreId = storeid
		db.GetDB().Create(&storeinfo)
		return storeid
	}
	return storeinfos[0].StoreId
}

func LogerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		//开始时间
		startTime := time.Now()
		//处理请求
		c.Next()
		//结束时间
		endTime := time.Now()
		// 执行时间
		latencyTime := endTime.Sub(startTime)
		//请求方式
		reqMethod := c.Request.Method
		//请求路由
		reqUrl := c.Request.RequestURI
		//状态码
		statusCode := c.Writer.Status()
		//请求ip
		clientIP := c.ClientIP()
		// 日志格式
		logcat.Info("req请求参数", "status_code:", statusCode, "latency_time:", latencyTime, "client_ip:", clientIP, "req_method:", reqMethod, "req_uri", reqUrl)
	}
}
